package cn.edu.sdju.wanglo1911.team10.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.server.ResponseStatusException;

import cn.edu.sdju.wanglo1911.team10.po.Book;
import cn.edu.sdju.wanglo1911.team10.po.QueryOption;
import cn.edu.sdju.wanglo1911.team10.service.BookService;

@Controller
public class BookController {
	
	@Autowired
	private BookService bookService;
	
	
	@RequestMapping(value = "/",method = {RequestMethod.GET})
	public String home(HttpServletRequest request, HttpSession session, Model model) {
		List<Book> books = bookService.getLimitBooks(10);
		model.addAttribute("books", books);
		model.addAttribute("account", session.getAttribute("account"));
		return "index";
	}
	
	@RequestMapping(value = "/search",method = {RequestMethod.GET})
	public String searchBook(@RequestParam("q") String query, Integer dir,Model model) {
		model.addAttribute("query", query);
		if (dir == null) {
			dir = 0;
		}
		QueryOption queryOption = new QueryOption();
		queryOption.setQuery(query);
		queryOption.setDir(dir);
		
		List<Book> books =  bookService.searchBooks(queryOption);
		model.addAttribute("books", books);
		model.addAttribute("dir", dir);
		return "search_result";
	}
	
	@RequestMapping(value = "/book/{id}",method = {RequestMethod.GET})
	public String bookView(HttpServletRequest request,@PathVariable String id, HttpSession session,Model model) {
		Book book = bookService.getBookById(id);
		if (book == null) {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND);
		}
		model.addAttribute("book", book);
		model.addAttribute("account", session.getAttribute("account"));
		return "item";
	}
	
	
}
